package com.briup.es.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.briup.es.auth.SecurityUserContext;
import com.briup.es.config.exception.ServiceException;
import com.briup.es.config.response.ResultCode;
import com.briup.es.domain.bean.Address;
import com.briup.es.domain.bean.User;
import com.briup.es.domain.vo.AddressVO;
import com.briup.es.mapper.UserMapper;
import com.briup.es.service.AddressService;
import com.briup.es.mapper.AddressMapper;
import com.briup.es.util.BeanUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

@Service
@RequiredArgsConstructor
public class AddressServiceImpl extends ServiceImpl<AddressMapper, Address>
        implements AddressService {

    private final UserMapper userMapper;

    @Override
    public List<AddressVO> listAddressByUserId(Integer userId) {
        // 根据用户id，查询该用户的地址
        LambdaQueryWrapper<Address> wrapper = new LambdaQueryWrapper<Address>()
                .eq(Address::getUserId, userId);
        List<Address> addresses = baseMapper.selectList(wrapper);
        // 根据用户id查询用户信息，内部包含用户的默认地址id
        User user = userMapper.selectById(userId);
        // 进行bean转换
        return addresses.stream().map(address -> {
            AddressVO addressVO = BeanUtil.bean2VO(address, AddressVO.class);
            // 当前地址的id与当前登录用户的默认地址id进行比较，确定当前地址是否为默认地址
            addressVO.setDefaultValue(Objects.equals(addressVO.getId(),
                    user.getDefaultAddressId()));
            return addressVO;
        }).toList();
    }

    @Override
    public void modifyDefaultAddress(Integer addressId, String action) {
        // 根据地址id以及当前登录用户的id判断该地址是否属于当前用户
        Integer userId = SecurityUserContext.currentUserId();

        // 根据地址id及用户id查询指定的地址是否存在
        LambdaQueryWrapper<Address> wrapper = new LambdaQueryWrapper<Address>()
                .eq(Address::getUserId, userId)
                .eq(Address::getId, addressId);
        Address address = baseMapper.selectOne(wrapper);
        if (address == null) {
            throw new ServiceException(ResultCode.ADDRESS_IS_NOT_FOUND);
        }

        // 修改当前用户的默认地址，根据是否取消默认地址的动作，决定默认地址修改的内容是什么
        LambdaUpdateWrapper<User> updateWrapper = new LambdaUpdateWrapper<User>()
                .eq(User::getId, userId)
                .set(User::getDefaultAddressId,
                "cancel".equals(action) ? null : addressId);
        userMapper.update(updateWrapper);
    }
}




